package com.amumu.drama.common.modules.sumapay.servlet;

import cn.hutool.json.JSONUtil;
import com.amumu.drama.common.modules.sumapay.tools.MD5Tools;
import com.amumu.drama.common.modules.sumapay.tools.MySSLHostnameVerifier;
import com.amumu.drama.common.modules.sumapay.tools.MyX509TrustManager;
import com.quickpay.model.AliPayModel;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class IAZ1002_Servlet extends HttpServlet {

    /**
     *
     */
    private static final long serialVersionUID = 1L;

    /*
     * public static void main(String[] args) throws IOException, URISyntaxException
     * { httpPost(); }
     */
    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        doPost(request, response);
    }

    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, ClientProtocolException {
        response.setContentType("text/html;charset=GBK");
        request.setCharacterEncoding("GBK");
        response.setCharacterEncoding("GBK");
        PrintWriter out = response.getWriter();
        // 得到AgreementPaySend，并获取跳转url
        try {

            String requestType = request.getParameter("requestType");
            String requestId = request.getParameter("requestId");
            String merchantCode = request.getParameter("merchantCode");
            String totalBizType = request.getParameter("totalBizType");
            String totalPrice = request.getParameter("totalPrice");
            String goodsDesc = request.getParameter("goodsDesc");
            String rePayTimeOut = request.getParameter("rePayTimeOut");
            String noticeUrl = request.getParameter("noticeUrl");
            String passThrough = request.getParameter("passThrough");

            String productId = request.getParameter("productId");
            String productName = request.getParameter("productName");
            String fund = request.getParameter("fund");
            String merAcct = request.getParameter("merAcct");
            String bizType = request.getParameter("bizType");
            String productNumber = request.getParameter("productNumber");

            String merKey = request.getParameter("merKey");

            StringBuilder sb = new StringBuilder();
            sb.append(requestType);
            sb.append(requestId);
            sb.append(merchantCode);
            sb.append(totalBizType);
            sb.append(totalPrice);
            sb.append(goodsDesc);
            sb.append(rePayTimeOut);
            sb.append(noticeUrl);
            sb.append(passThrough);
            String signature = MD5Tools.Md5(sb.toString(), merKey);
            List<NameValuePair> nvps = new ArrayList<NameValuePair>();

            nvps.add(new BasicNameValuePair("requestType", requestType));
            nvps.add(new BasicNameValuePair("requestId", requestId));
            nvps.add(new BasicNameValuePair("merchantCode", merchantCode));
            nvps.add(new BasicNameValuePair("totalBizType", totalBizType));
            nvps.add(new BasicNameValuePair("totalPrice", totalPrice));
            nvps.add(new BasicNameValuePair("goodsDesc", goodsDesc));
            nvps.add(new BasicNameValuePair("rePayTimeOut", rePayTimeOut));
            nvps.add(new BasicNameValuePair("noticeUrl", noticeUrl));
            nvps.add(new BasicNameValuePair("passThrough", passThrough));
            nvps.add(new BasicNameValuePair("signature", signature));
            nvps.add(new BasicNameValuePair("productId", productId));
            nvps.add(new BasicNameValuePair("productName", productName));
            nvps.add(new BasicNameValuePair("fund", fund));
            nvps.add(new BasicNameValuePair("merAcct", merAcct));
            nvps.add(new BasicNameValuePair("bizType", bizType));
            nvps.add(new BasicNameValuePair("productNumber", productNumber));
            System.out.println(signature + "=signature");

            SSLContext sslContext = null;

            sslContext = SSLContext.getInstance("TLSv1.2");

            X509TrustManager tm = new MyX509TrustManager();
            sslContext.init(null, new TrustManager[]{tm}, new java.security.SecureRandom());

            HttpClientBuilder httpClientBuilder = HttpClients.custom().setSSLContext(sslContext);

            HostnameVerifier hostnameVerifier = new MySSLHostnameVerifier();
            httpClientBuilder.setSSLHostnameVerifier(hostnameVerifier);

            HttpClient httpClient = httpClientBuilder.build();
            HttpPost post = new HttpPost("https://www.sumapay.com/aggregatePayMobile/merchantService.do");

            post.setEntity(new UrlEncodedFormEntity(nvps));

            CloseableHttpResponse responsePost = (CloseableHttpResponse) httpClient.execute(post);
            int status = responsePost.getStatusLine().getStatusCode();
            System.out.println(status);
            byte[] responseBody = null;
            String responseBody1 = "";
            Map<String, Object> resultMap;
            if (status != HttpStatus.SC_OK) {
                // TODO 请求失败，进行相应业务处理
                response.getOutputStream().write(("请求失败，http返回值：" + status).getBytes("GBK"));
                return;
            } else {
                // 获取返回值
                String result = EntityUtils.toString(responsePost.getEntity(), "GBK");
                String result2 = EntityUtils.toString(post.getEntity(), "GBK");
                System.out.println(result2 + "=result");
                resultMap = JSONUtil.parseObj(result).toBean(HashMap.class);
                post.releaseConnection();
            }
            System.out.println(resultMap + "=resultMap");
            requestId = (String) resultMap.get("requestId");

            String result1 = (String) resultMap.get("result");
            String codeUrl = (String) resultMap.get("codeUrl");
            String codeImgString = (String) resultMap.get("codeImgString");
            String payId = (String) resultMap.get("payId");
            String errorMsg = (String) resultMap.get("errorMsg");
            String returnSignature = (String) resultMap.get("resultSignature");
            System.out.println(errorMsg + "=errorMsg");
            StringBuilder returnSb = new StringBuilder();

            returnSb.append(requestId);
            returnSb.append(result1);
            returnSb.append(codeUrl);
            returnSb.append(codeImgString);
            returnSb.append(payId);
            returnSb.append(errorMsg);
            returnSb.append(passThrough);

            String returnSignStr = returnSb.toString();
            String signature2 = MD5Tools.Md5(returnSb.toString(), merKey);
            String signCheck;
            System.out.println(signature2 + "=signature2");
            System.out.println(returnSignature + "=returnSignature");
            if (signature2.equals(returnSignature)) {
                signCheck = "验签成功";
            } else {
                signCheck = "验签失败";
            }

            AliPayModel aliPayModel = new AliPayModel();

            aliPayModel.setRequestId(requestId);
            aliPayModel.setResult(result1);
            aliPayModel.setCodeUrl(codeUrl);
            aliPayModel.setCodeImgString(codeImgString);
            aliPayModel.setPayId(payId);
            aliPayModel.setPassThrough(passThrough);
            aliPayModel.setErrorMsg(errorMsg);
            aliPayModel.setReturnSignature(returnSignature);
            request.getSession().setAttribute("aliPayModel", aliPayModel);
            response.sendRedirect("IAZ1002_Sign.jsp");

            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void init() throws ServletException {
        // Put your code here
    }

}
